zsApp
.controller( 'userMechanismlController',["$scope", "$http", "$state", "$filter", "$cookies", "$location", function( $scope, $http, $state, $filter, $cookies, $location ){
	// 默认关闭弹窗
	$(".modal-backdrop").remove();
	// 储存ID
	$scope.userMechanismId = [];
	// 用于控制新增弹窗翻页
	$scope.currPage = true;

	// 检索
	$scope.retrieval = function() { 

		// 保存用户需要检索的数据
		$cookies.putObject( 'retrievalData', 
		{
			institutionName  : $scope.retrieval_institutionName || '', 		/* 机构名称（可为空）*/
			email 		     : $scope.retrieval_email || '',				/* 邮箱（可为空）*/
			province 		 : $scope.retrieval_province || '',				/* 省份（可为空）*/
			city 			 : $scope.retrieval_city || '',					/* 城市（可为空）*/
			startCreateTime  : $scope.retrieval_startCreateTime || '',		/* 开始注册时间（可为空）*/
			endCreateTime    : $scope.retrieval_endCreateTime || '',		/* 结束注册时间（可为空）*/
			startLoginTime   : $scope.retrieval_startLoginTime || '',		/* 开始登录时间（可为空）*/
			endLoginTime 	 : $scope.retrieval_endLoginTime || '',			/* 最后登录时间（可为空）*/
		});

		// 重新加载页面
		$state.go( "index.mechanism",{},{ reload:true } );
	}


	// 分页
	$scope.paginationConf = {
        currentPage 	: 1,
        totalItems		: 100,
        itemsPerPage 	: 4,
        pagesLength		: 15,
        perPageOptions	: [10, 20, 30, 40, 50],
        onChange: function() {

        	$scope.retrievalData = $cookies.get('retrievalData');

        	var self = this;
        	$scope.pagingData = {
        		queryType   	: $scope.queryType=($scope.retrievalData==undefined)?0:1,					    				
        		pageNumber  	: self.currentPage,  					
				pageSize 		: self.itemsPerPage, 	
        	}

        	$scope.pagingRetrievalData = angular.extend($scope.pagingData, angular.fromJson($scope.retrievalData));
        	if( (($scope.isRequestCurrentPage != self.currentPage) || ($scope.isRequestItemsPerPage != self.itemsPerPage)) && (new Date() - $scope.nowTime > 500) )
        	{	
        		$scope.nowTime = new Date();
				$http
				({
					url    		: $scope.zsUrl+'digitalhome-boss/admin/institutions/getList',
					method    	: 'POST',
					dataType  	: 'JSON',
					data   		: JSON.stringify($scope.pagingRetrievalData),
					contentType : 'application/json;charset=UTF-8', 
				})
				.then
				(
					function success(res) {
						if( '0000' == res.data.result_code ) 
						{
							// 角色组列表页面表格
							$scope.tabVal = res.data.result;
							// 遍历所有角色ID
							angular.element(res.data.result).each(function(i) {
								$scope.userMechanismId[i] = this.institutionId;
							});
							// 总共有多少条数据
							self.totalItems = res.data.length;
						}
						else
						{
							$scope.isNoData = false;
						}
						
					}, 
					function error(err) {
						$scope.isNoData = false;
						console.log(err);
					}
				);

				$scope.isRequestCurrentPage = self.currentPage;
				$scope.isRequestItemsPerPage = self.itemsPerPage;

			}
			
			// 是否清除缓存
			$scope.isRemove = true;
			if( $scope.isRemove )
			{
				$cookies.remove('retrievalData');
				$scope.isRemove = false;
			}
			
        }
    }
	
	// 确定新增（新增一条机构用户列表数据）
	$scope.confirmNewlyAdded = function() {
		// 新增一条机构用户列表（封装成JSON）
		var newlyAddedData = {
			userInstitutionId : '',
	        institutionId 	  : '',
	        userId 			  : '',
	        relation 		  : 1,
			institutions 	  : {
				institutionName          : $scope.newlyAddedInstitutionName,
				institutionDisplayName   : $scope.newlyAddedInstitutionDisplayName,
				institutionType 		 : $scope.newlyAddedInstitutionType,
				nature 					 : $scope.newlyAddedNature,
				industry 				 : $scope.newlyAddedIndustry,
				province  				 : $scope.newlyAddedProvince,
				city 					 : $scope.newlyAddedCity,
				address     			 : $scope.newlyAddedAddress,
				phone 					 : $scope.newlyAddedPhone,
				contactName 			 : $scope.newlyAddedContactName,
				postcode 				 : $scope.newlyAddedPostcode,
				description              : $scope.newlyAddedDescription,
				enabled 				 : $scope.newlyAddedEnabled,
			},
			pusers 			  : {
				userName 				 : $scope.newlyAddedUserName,
				displayName              : $scope.newlyAddedDisplayName,
				password          		 : $scope.newlyAddedPassword,
				email          		 	 : $scope.newlyAddedEmail,
				status          		 : $scope.newlyAddedStatus,
				isActivate          	 : $scope.newlyAddedIsActivate,
				isAutonym          		 : $scope.newlyAddedIsAutonym,
			},
			userInfos         : {

			},
		}

		$http
		({
			url       	: $scope.zsUrl+'digitalhome-boss/admin/institutions/add',
			method    	: 'POST',
			dataType  	: 'JSON',
			data   	    : JSON.stringify(newlyAddedData), 	/* 将JSON发送给服务器 */
			contentType : 'application/json;charset=UTF-8', 
 
		}).then(function success(res) {
			console.log(res.data.message);
			// 清空表单
			$scope.newlyAddedRoleGroupName = '';
			$scope.newlyAddedDescription = '';
			// 重新加载页面
			// $state.go("index.mechanism",{},{reload:true});
		},
		function error(err){
			console.log(err);
		});
		// 关闭窗口
		$('#newlyAdded').modal('hide');
	}

	// 详情（用于向用户展示从服务器获取的数据）
	$scope.details = function($event, $index) {
		$http
		({
			url    : $scope.zsUrl+'digitalhome-boss/admin/institutions/getInstitutionsInfo/'+$scope.userMechanismId[$index]+'',
			method : 'GET',
		})
		.then(
			function success(res) 
			{
				// 向用户展示从服务器获取到的数据
				$scope.details_institutionId 		 	= res.data.result.institutionId;
				$scope.details_parentId 	 		 	= res.data.result.parentId;
				$scope.details_institutionOrder      	= res.data.result.institutionOrder;
				$scope.details_institutionName 		 	= res.data.result.institutionName;
				$scope.details_institutionDisplayName 	= res.data.result.institutionDisplayName;
				$scope.details_institutionType 	 		= res.data.result.institutionType;
				$scope.details_nature 					= res.data.result.nature;
				$scope.details_industry 				= res.data.result.industry;
				$scope.details_province 				= res.data.result.province;
				$scope.details_city 					= res.data.result.city;
				$scope.details_address					= res.data.result.address;
				$scope.details_phone 					= res.data.result.phone;
				$scope.details_contactName 				= res.data.result.contactName;
				$scope.details_postcode 				= res.data.result.postcode;
				$scope.details_description 				= res.data.result.description;
				$scope.details_enabled 					= res.data.result.enabled;
				$scope.details_createDate	 			= $filter('date')(res.data.result.createDate,'yyyy年MM月dd日 HH:mm:ss');
				$scope.details_createUserId 			= res.data.result.createUserId;
				$scope.details_lastUpdatedDate 			= $filter('date')(res.data.result.lastUpdatedDate,'yyyy年MM月dd日 HH:mm:ss');
				$scope.details_lastUpdatedUserId 		= res.data.result.lastUpdatedUserId;
			},
			function error(err) 
			{
				console.log(err);
			}
		);
	}

	// 修改（调用接口与“详情”相同，用于向用户展示从服务器获取的数据）
	var __index = 0;
	$scope.edit = function($event, $index) {
		__index = $index;
		$http({
			url    : $scope.zsUrl+'digitalhome-boss/admin/institutions/getInstitutionsInfo/'+$scope.userMechanismId[$index]+'',
			method : 'POST',
		})
		.then(
			function success(res) {
				// 向用户展示从服务器获取到的数据
				$scope.edit_institutionId 		 	= res.data.result.institutionId;
				$scope.edit_parentId 	 		 	= res.data.result.parentId;
				$scope.edit_institutionOrder      	= res.data.result.institutionOrder;
				$scope.edit_institutionName 		= res.data.result.institutionName;
				$scope.edit_institutionDisplayName 	= res.data.result.institutionDisplayName;
				$scope.edit_institutionType 	 	= res.data.result.institutionType;
				$scope.edit_nature 					= res.data.result.nature;
				$scope.edit_industry 				= res.data.result.industry;
				$scope.edit_province 				= res.data.result.province;
				$scope.edit_city 					= res.data.result.city;
				$scope.edit_address					= res.data.result.address;
				$scope.edit_phone 					= res.data.result.phone;
				$scope.edit_contactName 			= res.data.result.contactName;
				$scope.edit_postcode 				= res.data.result.postcode;
				$scope.edit_description 			= res.data.result.description;
				$scope.edit_enabled 				= res.data.result.enabled;
				$scope.edit_createDate	 			= $filter('date')(res.data.result.createDate,'yyyy年MM月dd日 HH:mm:ss');
				$scope.edit_createUserId 			= res.data.result.createUserId;
				$scope.edit_lastUpdatedDate 		= $filter('date')(res.data.result.lastUpdatedDate,'yyyy年MM月dd日 HH:mm:ss');
				$scope.edit_lastUpdatedUserId 		= res.data.result.lastUpdatedUserId;

			},
			function error() {

			}
		);
	}

	// 确认修改（用于用户修改原有的数据）
	$scope.confirmEdit = function($event) {
		// 修改角色组名、描述（封装成JSON）
		var editData = {
			institutionId   	 	: $scope.userMechanismId[__index],
			parentId 			 	: $scope.edit_parentId,
			institutionOrder     	: $scope.edit_institutionOrder,
			institutionName      	: $scope.edit_institutionName,
			institutionDisplayName  : $scope.edit_institutionDisplayName,
			institutionType     	: $scope.edit_institutionType,
			nature     				: $scope.edit_nature,
			industry     			: $scope.edit_industry,
			province     			: $scope.edit_province,
			city     				: $scope.edit_city,
			address     			: $scope.edit_address,
			phone     				: $scope.edit_phone,
			contactName     		: $scope.edit_contactName,
			postcode     			: $scope.edit_postcode,
			description     		: $scope.edit_description,
			enabled     			: $scope.edit_enabled,
			createDate     			: $scope.edit_createDate,
			createUserId     		: $scope.edit_createUserId,
			lastUpdatedDate     	: $scope.edit_lastUpdatedDate,
			lastUpdatedUserId     	: $scope.edit_lastUpdatedUserId,
		}

		$http(
		{
			url   	: $scope.zsUrl+'digitalhome-boss/admin/institutions/modify',
			method  : 'POST',
			data    : editData, /* 将JSON发送给服务器 */
		})
		.then(function success(res) 
		{
			console.log(res.status);
			// 重新加载页面
			$state.go("index.mechanism",{},{reload:true});
		}, 
		function error(err) 
		{
			console.log(err);
		});
		$('#edit').modal('hide');
	}

	// 二级机构信息（用于查看二级机构信息）
	$scope.subId = [];
	$scope.packing = function($event, $index) {
		$http({

			url 	: $scope.zsUrl+'digitalhome-boss/admin/institutions/getSublevelInfo/'+$scope.userMechanismId[$index]+'',
			method	: 'GET',

		}).success(function(res) {

			console.log(res.result);
			console.log(res.result[0].institutionId);

			// 下级机构信息列表页面表格
			$scope.subTabVal = res.result;

			// 遍历所有角色ID
			angular.forEach(res.result, function(obj, i) {
				
				$scope.subId = obj.institutionId;

			});

			// 判断数组是否有下级机构
			if( 0 == res.result.length ) {
				$scope.isNoDataSub = false;
			}
			else 
			{
				$scope.isNoDataSub = true;
			}

			

		}).error(function(err) {
			console.log(err);
		});

	}

	// 下级机构信息（用于查看下级机构信息，无限遍历）
	$scope.subPacking = function($event, $index) {
		$http({

			url 	: $scope.zsUrl+'digitalhome-boss/admin/institutions/getSublevelInfo/'+$scope.subId[$index]+'',
			method	: 'GET',

		}).success(function(res) {

			console.log(res.result);

			// 下级机构信息列表页面表格
			$scope.subTabVal = res.result;

			// 遍历所有角色ID
			angular.forEach(res.result, function(obj, i) {
				$scope.subId = obj.institutionId;
			});
			
			
			

		}).error(function() {

		});
	}

	// 确定新增（上一页）
	$scope.prev = function() {
		$scope.currPage = true;
	}

	// 确定新增（下一页）
	$scope.next = function() {
		$scope.currPage = false;
	}
               
}])